<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>角色管理</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    .table-container {
      margin: 20px;
    }
    .search-box {
      margin-bottom: 20px;
    }
    .add-btn {
      float: right;
    }
    .pagination-info {
      margin-top: 10px;
    }
    .modal-header {
      background-color: #f8f9fa;
      border-bottom: 1px solid #dee2e6;
    }
    .form-group {
      margin-bottom: 15px;
    }
  </style>
</head>
<body>
<div class="container-fluid">
  <h2>角色列表</h2>

  <!-- 搜索框和新增按钮 -->
  <div class="row search-box">
    <div class="col-md-6">
      <div class="input-group">
        <input type="text" id="userNameSearch" class="form-control" placeholder="请输入角色名称">
        <button class="btn btn-primary" id="searchBtn">搜索</button>
      </div>
    </div>
    <div class="col-md-6">
      <button class="btn btn-success add-btn" id="addRoleBtn">新增角色</button>
    </div>
  </div>

  <!-- 角色列表表格 -->
  <div class="table-container">
    <table class="table table-striped table-bordered table-hover">
      <thead class="table-dark">
      <tr>
        <th>序号</th>
        <th>角色名称</th>
        <th>身份证号</th>
        <th>邮箱</th>
        <th>联系电话</th>
        <th>居住地址</th>
        <th>密码</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody id="roleTableBody">
      <!-- 数据将通过AJAX动态加载 -->
      </tbody>
    </table>
  </div>

  <!-- 分页控件 -->
  <div class="row">
    <div class="col-md-6 pagination-info">
      <span id="paginationInfo"></span>
    </div>
    <div class="col-md-6">
      <nav aria-label="Page navigation">
        <ul class="pagination justify-content-end" id="pagination">
          <!-- 分页按钮将通过JS动态生成 -->
        </ul>
      </nav>
    </div>
  </div>
</div>

<!-- 新增/编辑角色模态框 -->
<div class="modal fade" id="roleModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalTitle">新增角色</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="roleForm">
          <input type="hidden" id="userId">
          <div class="form-group">
            <label for="userName" class="form-label">角色名称</label>
            <input type="text" class="form-control" id="userName" required>
          </div>
          <div class="form-group">
            <label for="pid" class="form-label">身份证号</label>
            <input type="text" class="form-control" id="pid">
          </div>
          <div class="form-group">
            <label for="email" class="form-label">邮箱</label>
            <input type="email" class="form-control" id="email">
          </div>
          <div class="form-group">
            <label for="mobile" class="form-label">联系电话</label>
            <input type="tel" class="form-control" id="mobile">
          </div>
          <div class="form-group">
            <label for="address" class="form-label">居住地址</label>
            <input type="text" class="form-control" id="address">
          </div>
          <div class="form-group">
            <label for="password" class="form-label">密码</label>
            <input type="password" class="form-control" id="password">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="saveRoleBtn">保存</button>
      </div>
    </div>
  </div>
</div>

<!-- 引入Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
  $(document).ready(function() {
    // 当前页码和每页大小
    let currentPage = 1;
    const pageSize = 10;
    const roleModal = new bootstrap.Modal(document.getElementById('roleModal'));

    // 页面加载时获取角色列表
    getRoleList(currentPage, pageSize);

    // 搜索按钮点击事件
    $('#searchBtn').click(function() {
      currentPage = 1;
      getRoleList(currentPage, pageSize);
    });

    // 回车键触发搜索
    $('#userNameSearch').keypress(function(e) {
      if(e.which === 13) {
        currentPage = 1;
        getRoleList(currentPage, pageSize);
      }
    });

    // 新增角色按钮点击事件
    $('#addRoleBtn').click(function() {
      $('#roleForm')[0].reset();
      $('#modalTitle').text('新增角色');
      $('#userId').val('');
      roleModal.show();
    });

    // 保存角色按钮点击事件
    $('#saveRoleBtn').click(function() {
      saveRole();
    });

    // 获取角色列表函数
    function getRoleList(page, size) {
      const userName = $('#userNameSearch').val();

      $.ajax({
        url: '/system/sysUser/pageRole',
        type: 'GET',
        data: {
          current: page,
          size: size,
          userName: userName
        },
        dataType: 'json',
        success: function(response) {
          if(response.success) {
            renderRoleTable(response.data.records);
            renderPagination(response.data);
          } else {
            alert('获取角色列表失败: ' + response.message);
          }
        },
        error: function(xhr, status, error) {
          alert('请求失败: ' + error);
        }
      });
    }

    // 渲染角色表格
    function renderRoleTable(roles) {
      const $tbody = $('#roleTableBody');
      $tbody.empty();

      if(roles.length === 0) {
        $tbody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
        return;
      }

      $.each(roles, function(index, role) {
        const row = `
          <tr>
            <td>${role.userId}</td>
            <td>${role.userName || '-'}</td>
            <td>${role.pid || '-'}</td>
            <td>${role.email || '-'}</td>
            <td>${role.mobile || '-'}</td>
            <td>${role.address || '-'}</td>
            <td>${role.password ? '******' : '-'}</td>
            <td>
              <button class="btn btn-sm btn-primary edit-btn" data-id="${role.userId}">编辑</button>
              <button class="btn btn-sm btn-danger delete-btn" data-id="${role.userId}">删除</button>
            </td>
          </tr>
        `;
        $tbody.append(row);
      });

      // 绑定编辑和删除按钮事件
      $('.edit-btn').click(function() {
        const roleId = $(this).data('id');
        editRole(roleId);
      });

      $('.delete-btn').click(function() {
        const roleId = $(this).data('id');
        deleteRole(roleId);
      });
    }

    // 渲染分页控件
    function renderPagination(pageInfo) {
      const $pagination = $('#pagination');
      $pagination.empty();

      // 更新分页信息
      $('#paginationInfo').text(`共 ${pageInfo.total} 条记录，当前显示 ${pageInfo.current} / ${pageInfo.pages} 页`);

      // 上一页按钮
      const prevDisabled = pageInfo.current === 1 ? 'disabled' : '';
      $pagination.append(`
        <li class="page-item ${prevDisabled}">
          <a class="page-link" href="#" aria-label="Previous" data-page="${pageInfo.current - 1}">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>
      `);

      // 页码按钮
      for(let i = 1; i <= pageInfo.pages; i++) {
        const active = i === pageInfo.current ? 'active' : '';
        $pagination.append(`
          <li class="page-item ${active}">
            <a class="page-link" href="#" data-page="${i}">${i}</a>
          </li>
        `);
      }

      // 下一页按钮
      const nextDisabled = pageInfo.current === pageInfo.pages ? 'disabled' : '';
      $pagination.append(`
        <li class="page-item ${nextDisabled}">
          <a class="page-link" href="#" aria-label="Next" data-page="${pageInfo.current + 1}">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      `);

      // 绑定分页按钮点击事件
      $('.page-link').click(function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        if(page !== currentPage) {
          currentPage = page;
          getRoleList(currentPage, pageSize);
        }
      });
    }

    // 编辑角色
    function editRole(roleId) {
      $.ajax({
        url: '/system/sysUser/getById',
        type: 'GET',
        data: { userId: roleId },
        dataType: 'json',
        success: function(response) {
          if(response.success) {
            const role = response.data;
            $('#modalTitle').text('编辑角色');
            $('#userId').val(role.userId);
            $('#userName').val(role.userName);
            $('#pid').val(role.pid);
            $('#email').val(role.email);
            $('#mobile').val(role.mobile);
            $('#address').val(role.address);
            $('#password').val('');
            roleModal.show();
          } else {
            alert('获取角色信息失败: ' + response.message);
          }
        },
        error: function(xhr, status, error) {
          alert('请求失败: ' + error);
        }
      });
    }

    // 保存角色
    function saveRole() {
      const roleData = {
        userId: $('#userId').val(),
        userName: $('#userName').val(),
        pid: $('#pid').val(),
        email: $('#email').val(),
        mobile: $('#mobile').val(),
        address: $('#address').val(),
        password: $('#password').val()
      };

      const url = roleData.userId ? '/system/sysUser/update' : '/system/sysUser/save';
      const method = roleData.userId ? 'POST' : 'POST';

      $.ajax({
        url: url,
        type: method,
        contentType: 'application/json',
        data: JSON.stringify(roleData),
        dataType: 'json',
        success: function(response) {
          if(response.success) {
            roleModal.hide();
            getRoleList(currentPage, pageSize);
            alert('保存成功');
          } else {
            alert('保存失败: ' + (response.message || '未知错误'));
          }
        },
        error: function(xhr, status, error) {
          alert('请求失败: ' + error);
        }
      });
    }

    // 删除角色
    function deleteRole(roleId) {
      if(confirm('确定要删除这个角色吗？')) {
        $.ajax({
          url: '/system/sysUser/delete',
          type: 'POST',
          data: { userId: roleId },
          dataType: 'json',
          success: function(response) {
            if(response.success) {
              getRoleList(currentPage, pageSize);
              alert('删除成功');
            } else {
              alert('删除失败: ' + response.message);
            }
          },
          error: function(xhr, status, error) {
            alert('请求失败: ' + error);
          }
        });
      }
    }
  });
</script>
</body>
</html>